package com.sto.stoapp.activity.aviation;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.database.Cursor;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.activity.scanner.inquiry.InquiryQueryTable;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.dataprocess.ProcessScanCode;
import com.sto.stoapp.db.StoDataBase;
import com.sto.stoapp.db.StoDataBaseOperation;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.manager.CastManager;
import com.sto.stoapp.entity.DataBusinessEntity;
import com.sto.stoapp.entity.DownCastEntity;
import com.sto.stoapp.entity.ScanRecordInfoEntity;
import com.sto.stoapp.listener.OnBackClickListener;
import com.sto.stoapp.listener.StoOnItemClickListener;
import com.sto.stoapp.listener.StoOnKeyListener;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.status.EnumScanCode;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.util.BillFilterUtil;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.util.UnifiedStaticType;
import com.sto.stoapp.widget.BaseDialog;
import com.sto.stoapp.widget.StoHhmEditText;
import com.sto.stoapp.widget.StoHhmEditText.EditClickListener;
import com.sto.stoapp.widget.StoListenerActivity;

import java.util.ArrayList;
import java.util.List;

import sto.android.app.StoPdaKeyEvent;

public class StoAviationsPacketScanActivity extends StoListenerActivity {

	// private StoHhmEditText code;
	private EditText route, flight;
	private TextView need_bag, reality_bag;

	// // 包号默认标头
	// private String BAGHead = "900";
	private String flightCode = "";// 航班
	private String routeCode = "";// 路由
	// 应到包数和实到包数
	private int needBagCount, realityBagCount;
	private List<EditText> edit = new ArrayList<EditText>();
	private DataBusinessEntity dataBusiness;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sto_aviation_packet_scan);
		this.setTitleBottom(R.string.inbound_scan, HomeBroadAction.PICKER_BROAD);
		initWidget();
		initPointLayout(true);
		initListen();
		initScanListener();
		dataBusiness = new DataBusinessEntity();
		dataBusiness.initInsertData();
		initScanRecordAdapter(EnumTableNames.STATUS_TABLE_AVIATION_PICKER_PACKET);
	}

	private void initWidget() {
//		flight = (EditText) this.findViewById(R.id.avi_flight_text);
//		route = (EditText) this.findViewById(R.id.avi_route_text);
		code = (StoHhmEditText) this.findViewById(R.id.avi_bag_code_text);
//		need_bag = (TextView) this.findViewById(R.id.need_bag_num_text);
//		reality_bag = (TextView) this.findViewById(R.id.reality_bag_num_text);
		edit.add(code);
		addUploadTable(EnumTableNames.STATUS_TABLE_AVIATION_PICKER_PACKET);
	}

	/**
	 * 监听控件
	 */
	private void initListen() {
		// 包号
		code.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				onBackPressed();
			}

			@Override
			public void onEditClickListener(View v) {
				if (code.getText().toString().length() == 0) {
					Helper.showSoundToast(StoAviationsPacketScanActivity.this,
							getString(R.string.code_empty), false);
				} else {
					onScanResults(code.getText().toString());
				}
			}
		});

		// 点击列表查看详情
		getListView().setOnItemClickListener(new StoOnItemClickListener(this) {

			@Override
			public void KcOnItemClickListener(AdapterView<?> parent, View view,
					int position, long id) {
				showRecordDetail(
						((ScanRecordInfoEntity) getAdapter().getItem(position))
								.getRecordCode(), "tab_airt_tdb");
			}
		});

		getListView().setOnKeyListener(new StoOnKeyListener(this) {

			@Override
			public boolean OnKeyListener(View view, int position, KeyEvent event) {

				if (event.getAction() == KeyEvent.ACTION_UP
						&& event.getKeyCode() == StoPdaKeyEvent.KEYCODE_ENTER) {
					showRecordDetail(((ScanRecordInfoEntity) getAdapter()
							.getItem(position)).getRecordCode(), "tab_airt_tdb");
				}
				return false;
			}
		});

	}

	@Override
	public void onBackPressed() {
		showNotice();
	}

	private boolean CheckScanCode(String code) {
		boolean ret = false;
		EnumScanCode status = ProcessScanCode.getInstance(this)
				.ScanCodeResolve(code,
						EnumTableNames.STATUS_TABLE_AVIATION_PICKER_PACKET);
		switch (status) {
		// 条码空
		case CODE_EMPTY:
			break;

		// 非法条码
		case CODE_ILLEGAL:
			Helper.showSoundToast(this, getString(R.string.error_code), false);
			break;
		// 成功条码
		case CODE_WAY_BILL:
			ret = true;
			break;
		default:
			break;
		}
		return ret;
	}

	@SuppressLint("NewApi")
	private void processScanData() {
		try {
			if (!code.getText().toString().isEmpty()) {
//				if (queryRouteAndFlight(code.getText().toString())) {
//					isSaveRecordSuccess(code.getText().toString());
//				} else {
					routeCode = "";
					flightCode = "";
					/*
					 * 修改到包预报不存在时，不提示用户是否保存
					 * 
					 * @date 2014-05-28
					 */
					// showForceSaveAlert();

				//Add by wj过滤单号
				boolean isFilter= BillFilterUtil.isFilter(code.getText().toString().trim(),this);
				if(isFilter){
					showFilterDialog(code.getText().toString().trim());
					return;
				}
				//End by wj

					isSaveRecordSuccess(code.getText().toString());
//				}
			} else if (code.getText().toString().isEmpty()) {
				// 提示单号不能为空

			}
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("processScanData", e.getMessage());
		}
	}

	private void isSaveRecordSuccess(String codeNumber) {
		if (addPieceRecord(codeNumber)) {
			this.addCodeNumber();
			// SoundManager.getInstance(this).playSuccessSound();
			Helper.showSoundAndVibrator(this, true);
//			queryNeedCountByFlight(flightCode);
			routeCode = "";
			flightCode = "";
			addScanRecordInfo(codeNumber);
			code.setSelection(code.length());
		}
		// 提示插入数据失败
		else {
			Helper.showSoundToast(this, getString(R.string.code_repeat), false);
		}
	}

	private void showForceSaveAlert() {
		final String codeNumber = code.getText().toString();
		final BaseDialog dialog = new BaseDialog(this);
		dialog.setTitles(getString(R.string.bag_code_not_exist));
		dialog.show();
		dialog.getvMessage().setVisibility(View.GONE);
		dialog.getvPresentation().setVisibility(View.GONE);
		dialog.setOnBackClickListener(new OnBackClickListener() {

			@Override
			public void onBackClickListener(boolean res) {
				if (res) {
					isSaveRecordSuccess(codeNumber);
				}
				dialog.dismiss();

			}
		});
	}

	private boolean queryRouteAndFlight(String code) {
		try {
			DownCastEntity entity = CastManager.getInstance(this)
					.queryByBarCode(code);
			if (entity != null) {
				routeCode = entity.getRouteCode();
				flightCode = entity.getFlight();
				route.setText(routeCode);
				flight.setText(flightCode);
				queryNeedBagCount(flightCode);
				return true;
			} else {
				routeCode = "";
				flightCode = "";
			}
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("queryRouteAndFlight", e.getMessage());
		}
		return false;
	}

	private void queryNeedBagCount(String flight) {
		try {
			needBagCount = CastManager.getInstance(this)
					.queryNeedCountByFlight(flight);
			need_bag.setText("应到" + "      " + needBagCount);
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("queryNeedBagCount", e.getMessage());
		}
	}

	private void queryNeedCountByFlight(String flight) {
		if (flight.length() <= 0) { // 如果不是预报记录，实到加1
			realityBagCount += 1;
		} else {
			StoDataBase db = new StoDataBase(
					StoAviationsPacketScanActivity.this);
			synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
				String sql = "select count(*) from " + "tab_airt_tdb "
						+ "where " + " next_station = ? ";
				Cursor cursor = db.getSqliteDatabase(
						UnifiedStaticType.READ_DATABASE).rawQuery(sql,
						new String[] { flight });
				if (cursor != null && cursor.moveToFirst()) {
					realityBagCount = cursor.getInt(0);
				}
				db.closeCursor(cursor);
				db.closeDb(UnifiedStaticType.READ_DATABASE);
			}
		}
		reality_bag.setText("实到" + "      " + realityBagCount);
	}

	private void showRecordDetail(String barCode, String tableName) {
		String[] textMenu = new InquiryQueryTable(this).getCodeInquiryDetail(
				tableName, barCode, "%", 22);
		if (textMenu == null)
			return;
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("记录详情").setIcon(android.R.drawable.ic_dialog_info)
				.setNegativeButton("取消", null).setItems(textMenu, null);
		builder.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface dialog, int keyCode,
					KeyEvent event) {
				if (keyCode == StoPdaKeyEvent.KEYCODE_DEL
						&& event.getAction() == KeyEvent.ACTION_UP) {
					dialog.dismiss();
				}
				return false;
			}
		});
		builder.show();
	}

	private boolean addPieceRecord(String codeNumber) {
		boolean ret = false;
		dataBusiness.setCommand_type(EnumTableNames.STATUS_TABLE_AVIATION_PICKER_PACKET.getOpCode());
		dataBusiness.setBar_code_number(codeNumber);
		dataBusiness.setCodeType(getExpType(codeNumber));
		// 路由
		if (routeCode.length() <= 0) {
			dataBusiness.setReason_number("");
		} else {
			dataBusiness.setReason_number(routeCode);
		}
		// 航班
		if (flightCode.length() <= 0) {
			dataBusiness.setNext_station("");
		} else {
			dataBusiness.setNext_station(flightCode);
		}
		// 网点编号
		dataBusiness.setNet_code(StoFilePreference.getInstance(this)
				.getSiteCode());
		// 工号
		dataBusiness.setJob_number(StoFilePreference.getInstance(this)
				.getUserCode());
		ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
				EnumTableNames.STATUS_TABLE_AVIATION_PICKER_PACKET);
	
		return ret;
	}



	@Override
	protected void onDestroy() {
		edit.clear();
		edit = null;
		super.onDestroy();
	}

	@Override
	protected void handlerScanData(String scanData) {

		if (scanData != null && !scanData.equals("")) {
			String result = scanData;
			code.setText(result);
			code.setSelection(code.length());

			if (CheckScanCode(result)) {
				// // 包号
				// if (result.substring(0, 3).equals(BAGHead)) {
				// // 处理数据
				processScanData();
				// } else {
				// Helper.showSoundToast(
				// StoAviationsPacketScanActivity.this,
				// "包号错误", false);
				// }
			}
			code.setText("");
		} else {

		}

	
		
	}

}
